package online.keepon.document.web;

import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import online.keepon.document.common.ErrorInfo;
import online.keepon.document.common.PageInfo;
import online.keepon.document.common.Result;
import online.keepon.document.model.Article;
import online.keepon.document.model.ArticleType;
import online.keepon.document.model.dto.ArchivesNewsDTO;
import online.keepon.document.model.dto.ArticleItemDTO;
import online.keepon.document.model.dto.TagsDTO;
import online.keepon.document.service.ArticleService;
import online.keepon.document.service.ArticleTypeService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.*;

@Slf4j
@RestController
@RequestMapping(value = "/api/web")
public class WebController {
    private final ArticleService articleService;
    private final ArticleTypeService articleTypeService;

    public WebController(ArticleService articleService, ArticleTypeService articleTypeService) {
        this.articleService = articleService;
        this.articleTypeService = articleTypeService;
    }


    @GetMapping(value = "/image")
    public Result<JSONObject> image() {
        RestTemplate restTemplate = new RestTemplate();
        String url = "https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=zh-CN";
        String image = null;
        ResponseEntity<JSONObject> forEntity = restTemplate.getForEntity(url, JSONObject.class);
        if (forEntity.getStatusCode().equals(HttpStatus.OK) && forEntity.getBody() != null) {
            image = "https://cn.bing.com" + forEntity.getBody().getJSONArray("images").getJSONObject(0).getString("url");
        }
        return Result.ok(ErrorInfo.SUCCESS, forEntity.getBody());
    }

    @GetMapping(value = "/total")
    public Result<ArticleItemDTO> total() {
        ArticleItemDTO o = articleService.articleItemCount();
        Result<?> result = tagsList();
        String total = JSONObject.toJSONString(result.getPayload());
        o.setTags(JSONObject.parseObject(total).getInteger("total"));
        return Result.ok(o);
    }

    @ApiOperation(value = "详情")
    @GetMapping(value = "/article/detail/{id}")
    public Result<Article> document(@PathVariable String id) {
        Article document = articleService.selectByPrimaryKey(id);
        if (document == null) {
            return Result.ok(ErrorInfo.NOT_FOUND);
        }
        log.info("查看文章{}, tile: {}", id, document.getTitle());
        return Result.ok(document);
    }

    @ApiOperation(value = "列表")
    @GetMapping(value = "/article/list/{page}/{size}")
    public Result<PageInfo<Article>> list(@PathVariable Integer page, @PathVariable Integer size) {
        String status = "open";
        long total = articleService.countTotal(status);
        PageInfo<Article> document = articleService.selectAllByPage(PageInfo.Page.page(page, size, total), status);
        log.info("查看文章：总数{}，当前页：{},分页数：{}", total, document.getPageNum(), document.getPageSize());
        return Result.ok(document);
    }

    @ApiOperation(value = "搜索")
    @GetMapping(value = "/article/search/{page}/{size}/{search}")
    public Result<PageInfo<Article>> search(@PathVariable Integer page, @PathVariable Integer size, @PathVariable String search) {
        long total = articleService.countSearchTotal(search);
        PageInfo<Article> document = articleService.selectAllSearchByPage(PageInfo.Page.page(page, size, total), search);
        return Result.ok(document);
    }

    @ApiOperation(value = "文章分类列表")
    @GetMapping(value = "/article/categories/{categories}/{page}/{size}")
    public Result<PageInfo<Article>> articleCategoriesList(@PathVariable Integer page, @PathVariable Integer size, @PathVariable String categories) {
        long total = articleService.countCategoriesTotal(categories);
        PageInfo<Article> document = articleService.selectAllCategoriesByPage(PageInfo.Page.page(page, size, total), categories);
        log.info("查看文章：总数{}，当前页：{},分页数：{}", total, document.getPageNum(), document.getPageSize());
        return Result.ok(document);
    }

    @ApiOperation(value = "最新文章")
    @GetMapping(value = "/articles/news")
    public Result<List<Article>> newArticles() {
        List<Article> articles = articleService.selectArticlesNews();
        return Result.ok(articles);
    }


    @ApiOperation(value = "分类")
    @GetMapping(value = "/categories/news")
    public Result<?> categories() {
        List<ArticleType> articleTypes = articleTypeService.selectCategories();
        return Result.ok(articleTypes);
    }

    @ApiOperation(value = "分类")
    @GetMapping(value = "/categories/list/{page}/{size}")
    public Result<PageInfo<ArticleType>> categoriesList(@PathVariable Integer page, @PathVariable Integer size) {
        long total = articleTypeService.countCategoriesTotal();
        PageInfo<ArticleType> documentType = articleTypeService.selectAllCategoriesByPage(PageInfo.Page.page(page, size, total));
        return Result.ok(documentType);
    }

    @ApiOperation(value = "归档")
    @GetMapping(value = "/archives/news")
    public Result<List<ArchivesNewsDTO>> archives() {
        List<ArchivesNewsDTO> archivesNews = articleService.selectArticleArchivesNews();
        return Result.ok(archivesNews);
    }

    @ApiOperation(value = "归档")
    @GetMapping(value = "/archives/list/{page}/{size}")
    public Result<PageInfo<ArchivesNewsDTO>> archivesList(@PathVariable Integer page, @PathVariable Integer size) {
        long total = articleService.selectArticleArchivesCount();
        PageInfo<ArchivesNewsDTO> archivesNews = articleService.selectArticleArchives(PageInfo.Page.page(page, size, total));
        return Result.ok(archivesNews);
    }

    @ApiOperation(value = "归档")
    @GetMapping(value = "/archives/list/{condition}/{page}/{size}")
    public Result<PageInfo<ArchivesNewsDTO>> archivesConditionList(@PathVariable Integer page, @PathVariable Integer size, @PathVariable String condition) {
        long total = articleService.selectArticleArchivesConditionCount(condition);
        PageInfo<ArchivesNewsDTO> archivesNews = articleService.selectArticleArchivesCondition(PageInfo.Page.page(page, size, total), condition);
        return Result.ok(archivesNews);
    }

    @ApiOperation(value = "标签")
    @GetMapping(value = "/tags")
    public Result<?> tagsList() {
        List<TagsDTO> list = articleService.selectAllTags();
        Set<String> tagsDTOS = new HashSet<>();
        for (TagsDTO tagsDTO : list) {
            String[] split = tagsDTO.getTag().split(",");
            if (split.length == 0) {
                tagsDTOS.add(tagsDTO.getTag());
            }
            if (split.length != 0) {
                tagsDTOS.addAll(Arrays.asList(split));
            }
        }
        int size = tagsDTOS.size();
        Map<String, Object> map = new HashMap<>();
        map.put("total", size);
        map.put("tags", tagsDTOS);
        return Result.ok(map);
    }

    @ApiOperation(value = "文章标签列表")
    @GetMapping(value = "/article/tags/{tags}/{page}/{size}")
    public Result<PageInfo<Article>> articleTagsList(@PathVariable Integer page, @PathVariable Integer size, @PathVariable String tags) {
        long total = articleService.countTagsTotal(tags);
        PageInfo<Article> document = articleService.selectAllTagsByPage(PageInfo.Page.page(page, size, total), tags);
        log.info("查看文章：总数{}，当前页：{},分页数：{}", total, document.getPageNum(), document.getPageSize());
        return Result.ok(document);
    }
}
